<?php

namespace app\common\model;


class AdminUser extends Base
{
    protected $hidden = ['password'];
    public static $status = [
        -1 => '锁定',
        1  => '激活',
        0  => '未激活'];

    /**
     * 设置密码
     * @param $value
     * @return string
     */
    public function setPasswordAttr($value)
    {
        if($value){
            return buildPassword($value);
        }
        return false;
    }

    /**
     * 获取角色名称
     * @param $value
     * @param $data
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRolenameAttr($value, $data)
    {
        $m    = new AdminUserRole();
        $info = $m->field('name')->whereIn('id', rtrim($data['role_ids'], ','))->select();
        foreach ($info as $item) {
            $value .= $item['name'] . ',';
        }
        $value = rtrim($value, ',');
        return $value;
    }

    public function getStatusnameAttr($value, $data)
    {
        return isset(self::$status[$data['status']]) ? self::$status[$data['status']] : '未知';
    }

    /**
     * 通过uid获取用户信息
     * @param int $uid
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo(int $uid)
    {
        $rs = $this->where("id", "=", $uid)->find();
        return $rs;
    }

    /**
     * 用户登录
     * @param string $username
     * @param string $password
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(string $username, string $password)
    {
        $rs = $this->where(['username' => $username, 'password' => buildPassword($password)])->find();
        return $rs;
    }
}
